package com.vichat.common.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;

public class UdpUtil {
	
	private static DatagramSocket _ds = null;
	
	private static final int TIMEOUT = 50000; // 设置接收数据的超时时间
	
	public static void sendUdp(String pxyip,int pxyport, byte[] indata) throws Exception{
		DatagramSocket clids = UdpUtil.getClisocket();
		if(clids!=null){
			InetAddress ipAddress = InetAddress.getByName(pxyip);
			InetSocketAddress loc = new InetSocketAddress(ipAddress, pxyport);
			DatagramPacket dp_send = new DatagramPacket(indata, indata.length, loc);
			clids.send(dp_send);
		}else{
			throw new Exception("发送失败,客户端创建失败");
		}
	}
	
	public synchronized static DatagramSocket getClisocket(){
		try{
			if(_ds==null || _ds.isClosed()){
				_ds = new DatagramSocket(9000);
				_ds.setSoTimeout(TIMEOUT);
			}
		}catch(Exception e){
			System.out.print("获取客户端接口失败"+e.toString());
		}
		return _ds;
	}

}
